<?php
/**
 * Geneone: Content Management Framework
 * JSON Web Services Page
 *
 * http://geneone.neondragon.net/
 *
 * @package Geneone
 * @author Khlo
 * @version 1.0
 * @copyright 2004-2006 Geneone Development Team
 */
 
/* All your errors are belong to us */
error_reporting (E_ALL);

/* Load relevant config file */
require ("configs/servers.php");

if (GENEONE_MULTIPLE_SERVER AND isset($gene_servers[$_SERVER['HTTP_HOST']])) {
	require_once ("configs/".$gene_servers[$_SERVER['HTTP_HOST']].".php");
} else {
	require ("configs/default.php");
}

/* Load required core libraries */
define ("IN_GENE", TRUE);
require ("loader.php");

function loadAuth() {
	$auth =& Gene::getAuth();
	$user =& Gene::getUser();
}

header ("Content-Type: text/javascript");

$namespaces = Gene::getSetting("namespaces");

$ns = Gene_Request::getString("service", GENE_REQUEST_GET);
$method = Gene_Request::getString("method", GENE_REQUEST_GET);
if (isset($namespaces[$ns])) {
	require_once ("Gene/Namespace/".ucfirst(strtolower($ns)).".php");
	$nsclass = "Gene_Namespace_".$ns;
	$results = array();
	
	if ($r = call_user_func(array($nsclass, "runWebServices"), $method)) {
		echo generateJSON($r);
	} else {
		exit();
	}
}

function generateJSON($results) {
	$expressions = array();
	
	// Determine whether this $results array has numeric keys (JSON array) or
	// named keys (JSON object).
	if (array_keys($results) !== range(0, count($results)-1)) {
		$named = true;
	} else {
		$named = false;
	}
	
	foreach ($results as $j => $k) {
		if ($named) {
			$value = '"'.addslashes($j).'":';
		} else {
			$value = '';
		}
		
		if (is_array($k)) {
			$value .= generateJSON($k);
		} else if (is_bool($k)) {
			if ($k) {
				$value .= "true";
			} else {
				$value .= "false";
			}
		} else if (is_int($k)) {
			$value .= $k;
		} else {
			$value .= '"'.addslashes($k).'"';
		}
		
		$expressions[] = $value;
	}
	
	if ($named) {
		return "{".implode(",", $expressions)."}";
	} else {
		return "[".implode(",", $expressions)."]";
	}
}

/* cleanup */
Gene_Session::shutdown();
$db->disconnect();
 
?>